<template>
  <div class="app-container documentation-container">
    <div class="top">
      <el-form ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px" :model="enterprise">
        <el-row>
          <el-col :span="10">
            <div class="grid-content bg-purple">
              <el-form-item label="注册类型">
                <el-select v-model="enterprise.type" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="电话（账号）" prop="Telephone">
                <el-input v-model="enterprise.Telephone" type="number" width="100" />
              </el-form-item>
              <el-form-item label="初始密码" prop="pwd">
                <el-input
                  v-model="enterprise.pwd"
                />
                <el-button v-if="typefalg == true" type="warning" size="small" @click.native="restpassword">重置密码</el-button>
              </el-form-item>
              <el-form-item label="位置序号">
                <el-input v-model="enterprise.order" type="number" />
              </el-form-item>
              <el-form-item label="地图定位" prop="keeper">
                <div class="amap-page-container">
                  <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult" />
                  <el-amap vid="amapDemo" :center="mapCenter" :zoom="12" class="amap-demo">
                    <el-amap-marker v-for="marker in markers" :position="marker" />
                  </el-amap>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="grid-content bg-purple-light" />
          </el-col>
          <el-col :span="10">
            <div class="grid-content bg-purple-light">
              <el-form-item label="站点名称">
                <el-input v-model="enterprise.name" />
              </el-form-item>
              <el-form-item label="站点编号">
                <el-input v-model="enterprise.num" />
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="enterprise.address" />
              </el-form-item>
              <el-form-item label="负责人" prop="keeper">
                <el-input v-model="enterprise.keeper" />
              </el-form-item>

              <el-form-item label="">
                <el-button type="primary" size="small" @click.native="onSubmit('ruleForm')">{{ falg_text }}</el-button>
                <el-button v-if="submit" type="success" size="small" class="sub_button" @click.native="onImage">添加图片</el-button>
                <el-button v-if="submit" type="warning" size="small" class="sub_button" @click.native="onintroduction">添加企业介绍</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog title="添加站点图片" width="40%" :visible.sync="dialogTableVisible">
      <el-form :label-position="labelPosition" label-width="100px">
        <el-form-item label="站点首页图">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="ID_BACK"
          >
            <img v-if="IDfanmianMianimageUrl" :src="IDfanmianMianimageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="站点详情图">
          <el-upload
            class="upload-demo"
            action=""
            :before-remove="handleRemove"
            :before-upload="beforeUpload"
            name="image"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="添加站点介绍" width="70%" :visible.sync="qiyes">
      <tinymce v-model="content" :goodsid="IDother" :height="300" />
      <el-button size="small" type="primary" @click.native="addsiteinfo">添加</el-button>
    </el-dialog>
  </div>
</template>
<script>
import {
  mapGetters
} from 'vuex'
import Tinymce from '@/components/Tinymce'
export default {
  components: {
    mapGetters,
    Tinymce
  },
  props: {},
  data() {
    return {
      // 站点介绍
      content: '',
      qiyes: false,
      submit: false,
      // 地图
      markers: [
        [121.59996, 31.197646],
        [121.40018, 31.197622],
        [121.69991, 31.207649]
      ],
      searchOption: {
        city: '中国',
        citylimit: true
      },
      mapCenter: [121.59996, 31.197646],
      // 以上是地图
      imgarr: {},
      IDfanmianMianimageUrl: '', // 添加站点图片
      falg_text: '注册',
      typefalg: false, // false 导航进入 true 编辑修改
      dataval: {},
      dialogTableVisible: false,
      IDPositive: this.$ENV.IDPOSITIVE,
      IDBACK: this.$ENV.IDBACK,
      IDother: '', // 用户ID
      imgval: {},
      labelPosition: 'right',
      enterprise: {
        type: '',
        Telephone: '',
        pwd: '',
        order: '',
        name: '',
        num: '',
        address: '',
        keeper: ''
      },
      options: [{
        value: '1',
        label: '片区电商服务中心'
      }, {
        value: '2',
        label: '乡镇电商服务站'
      }, {
        value: '3',
        label: '村级电商服务点'
      }],

      fileList: [],
      rules: {
        Telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '电话号码长度不正确', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入企业地址', trigger: 'blur' }
        ],
        keeper: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {},
  methods: {
    addsiteinfo() {
      const data = {
        'id': this.IDother,
        'update': {
          'info': this.content
        }
      }
      this.$apifn.EditSite(data).then((ref) => {
        if (ref.data.Response.code == 200) {
          console.log(ref.data.Response)
          this.$message({
            message: '企业介绍添加成功',
            type: 'success'
          })
        }
      }).catch((res) => {

      })
    },
    onImage() { // 添加图片
      this.dialogTableVisible = true
    },
    onintroduction() { // 添加站点介绍
      this.qiyes = true
    },
    addMarker: function() {
      const lng = 121.5 + Math.round(Math.random() * 1000) / 10000
      const lat = 31.197646 + Math.round(Math.random() * 500) / 10000
      this.markers.push([lng, lat])
    },
    onSearchResult(pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          const { lng, lat } = poi
          lngSum += lng
          latSum += lat
          this.markers.push([poi.lng, poi.lat])
        })
        const center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.mapCenter = [center.lng, center.lat]
      }
    },
    handleRemove(file, fileList) { // 证书删除
      if (file && file.status === 'success') {
        console.log(fileList[0].url.slice(28))
        this.$imgFn.seend({ 'pathimg': fileList[0].url.slice(28) }).deleteimg(
          (ref) => {
            if (ref.status == 200) {
              if (ref.data.code == 200) {
                this.$notify({
                  title: ref.data.Massage,
                  type: 'success'
                })
                this.fileList = fileList
              }
            }
          }, (res) => {
            console.log(res)
          })
      }

      // deleteimg
    },
    beforeUpload(file) { // 证书图片上传
      if (this.$oneselfFn.IMAGEVAL(file)) {
        this.$imgFn.seend({ 'path': this.$ENV.TRACING + this.$ENV.ADMININISTRATION + this.IDother + this.$ENV.DETAILSTRACING, file }).addimg(
          (ref) => {
            if (ref.status == 200) {
              this.fileList.push({
                name: file.name,
                url: ref.data.imageURL + '/' + ref.data.imagePath
              })
            }
          }, (res) => {
            console.log(res)
          })
      } else {
        this.$notify({
          title: '警告',
          message: '图片大小不能超过2M',
          type: 'warning'
        })
      }
      return false
    },

    ID_BACK(file) { // 站点首页图
      if (this.$oneselfFn.IMAGEVAL(file)) {
        this.$imgFn.seend({ 'path': this.$ENV.TRACING + this.$ENV.ADMININISTRATION + this.IDother + this.$ENV.PAGETRACING, file }).update(
          (ref) => {
            if (ref.status == 200) {
              this.IDfanmianMianimageUrl = ref.data.imageURL + '/' + ref.data.imagePath
            }
          }, (res) => {
            console.log(res)
          })
      } else {
        this.$notify({
          title: '警告',
          message: '图片大小不能超过2M',
          type: 'warning'
        })
      }
      return false
    },
    inputval(val) { // 获取图片参数
      this.imgval = val
    },
    onSubmit(formName) { // 注册企业
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.typefalg == false) {
            console.log('注册')
            this.zhuce(this.enterprise)
          } else {
            this.xiugai(this.enterprise)
          }
        } else {
          return false
        }
      })
    },
    zhuce(val) { // 注册方法
      this.$apifn.AddSites(val).then((ref) => {
        if (ref.data.Response.code == 200) {
          this.dataval = ref.data.Response.data
          this.IDother = ref.data.Response.data.id.toString()
          this.dialogTableVisible = true
          console.log(this.IDother)
        }
      }).catch((res) => {
        this.errflag(res.request.response.errors)
      })
    },
    xiugai(val) { // 修改方法
      const data = {
        'id': val.id,
        'update': val
      }
      this.$apifn.EditSite(data).then((ref) => {
        if (ref.data.Response.code == 200) {
          this.dataval = ref.data.Response.data
          this.IDother = ref.data.Response.data.id.toString()
          this.dialogTableVisible = true
        }
      }).catch((res) => {
        this.errflag(JSON.parse(res.request.response).errors)
      })
    },
    errflag(err) { // 公共报错处理
      Object.keys(err).forEach((key) => {
        switch (key) {
          case 'Telephone':
            this.$notify({
              title: '电话号码可能重复',
              type: 'warning', offset: 50
            })
            break
          case 'name':
            this.$notify({
              title: '站点名称可能重复',
              type: 'warning', offset: 150
            })
            break
          case 'number':
            this.$notify({
              title: '站点编号可能重复',
              type: 'warning', offset: 200
            })
            break
          case 'num':
            this.$notify({
              title: '站点编号可重复',
              type: 'warning', offset: 150
            })
            break
        }
      })
    },
    restpassword() {
      this.$confirm('此操作会默认密码重置为电话号码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$apifn.ResetPassword({ 'id': this.qiyeenterprise.id.toString() }).then((ref) => {
          if (ref.data.Response.code == 200) {
            this.$message({
              type: 'success',
              message: ref.data.Response.message
            })
          }
        }).catch((res) => {
          // console.dir(res.request);
          if (res.request.status == 422) {
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    GET_IMG() { // 获取所有图片
      // select
      this.$imgFn.seend({ 'path': this.$ENV.TRACING + this.qiyeenterprise.id }).select(
        (ref) => {
          if (ref.status == 200) {
            const data = this.$oneselfFn.ImageHandlefunction(ref.data)
            console.log(data)
            if (data != {}) {
              if (data.detailsSite) {
                data.detailsSite.forEach((item, key) => {
                  this.fileList.push({
                    'name': key + 1,
                    'url': item
                  })
                })
              }
              this.IDfanmianMianimageUrl = data.PAGESite[0]
            }
          }
        }, (res) => {
          console.log(res)
        }
      )
    }
  },
  computed: {
    ...mapGetters([
      'qiyeenterprise'
    ])
  },
  created() {
    if (this.qiyeenterprise.id) {
      this.GET_IMG()
    }
  },
  mounted() {
    if (this.qiyeenterprise.id) {
      this.rules.pwd[0].required = false
      this.enterprise = this.qiyeenterprise
      this.typefalg = true
      this.qiyes = false
      this.submit = true
      this.falg_text = '修改'
      this.IDother = this.qiyeenterprise.id.toString()
      this.type = this.qiyeenterprise.type
      this.content = this.qiyeenterprise.info
    } else {

    }

    // console.log(this.$imgFn.seend({'path':'/a/a/1','file':"1"})._addimg());
    // console.log(this.$img);
    // this.$oneselfFn.deleteimage(this.$ENV.TRACING + this.qiyeenterprise.id+ this.$ENV.IDBACK);
  }
}
</script>
<style scoped>
  .amap-demo {
    height: 300px;
  }

  .search-box {
    position: absolute;
    top: 25px;
    left: 20px;
  }

  .amap-page-container {
    position: relative;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .app-container {

  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }

  }
  /*手机*/
  @media screen and (min-width: 100px) and (max-width: 960px) {
    .top {
      width: 100%;
      height: 147px;

    }

    .add_zhandian {
      width: 100%;
      height: 38px;
    }

    .selech {
      width: 100%;
      height: 50px;
    }
  }

  /*PC*/
  @media screen and (min-width: 960px) and (max-width: 1900px) {
    .top {
      width: 100%;
      height: 50px;
    }

    .add_zhandian {
      width: 20%;
      height: 100%;
      float: left;
    }

    .selech {
      width: 79%;
      height: 100%;
      float: right;

    }
  }

  .el-row {
    margin-bottom: 20px;

  &
  :last-child {
    margin-bottom: 0;
  }

  }
  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    /*background: #99a9bf;*/
  }

  .bg-purple {
    /*background: #d3dce6;*/
  }

  .bg-purple-light {
    /*background: #e5e9f2;*/
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    /*background-color: #f9fafc;*/
  }
</style>
